package com.kerbores.blog.module.user;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;

import com.kerbores.blog.constant.Constant;
import com.kerbores.blog.module.common.BaseModule;
import com.kerbores.blog.service.IUserService;
import com.kerbores.utils.common.CharSequence;
import com.kerbores.utils.entries.OperationState;
import com.kerbores.utils.entries.Result;

/**
 * @author 贵源 <br>
 *         create at 2014年10月19日
 */
@At("user")
public class UserModule extends BaseModule {

	@Inject
	private IUserService userService;

	@At("/login")
	@Ok("vel:user/login.vm")
	public Result loginForm() {
		return Result.success().setTitle("用户登录");
	}

	@At("/doLogin")
	public View doLogin(String userName, String password, boolean rememberMe) {
		Result loginResult = userService.login(userName, password);
		if (loginResult.getOperationState() == OperationState.SUCCESS) {
			if (rememberMe) {// 添加cookie
				_addCookie("userName", userName, 2592000);// 一个月
				_addCookie("password", CharSequence.encodeToString(password, Constant.COOKIED_PASSWORD_CALA_TIMES), 2592000);// 一个月
				_addCookie("rememberMe", rememberMe ? "1" : "0", 2592000);// 一个月
			}
			_putSession(Constant.LOGIN_USER_SESSION_KEY, loginResult.getNutMapData().get(Constant.LOGIN_USER_SESSION_KEY));
			return _renderRedirct("/");
		} else {
			return _renderVelocity("user/login.vm", Result.fail(loginResult.getNutMapData().getString("reason")).setTitle("用户登录"));
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.blog.module.common.BaseModule#_getNameSpace()
	 */
	@Override
	public String _getNameSpace() {
		return "user";
	}

}
